#coding: utf8

import sys
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)

import time
import pymongo
import redis

import logging
import logging.config

from exceptions import Exception

logging.config.fileConfig('./conf/log.conf')
rlog = logging.getLogger('root')


def cal_list_time_weight(list_time):
    try:
        timestamp = time.strptime(list_time, '%Y-%m-%d %H:%M:%S' ) #2011-10-17 21:38:51)
        timestamp = time.mktime(timestamp)
    except Exception as e:
        rlog.warning('parse list_time[%s] fail: %s' %(list_time, repr(e)))
        return 0
    time_interval = 1 + (time.time() - timestamp) / 86400 # days from list items
    w = 2000/time_interval
    return w


def cal_item_weight(item):
    w_time = cal_list_time_weight(item['list_time'])
    w_showcase = item['has_showcase'] and 1000 or 0
    w_discount = item['has_discount'] and 500 or 0
    w_price = float(item['price'])
    w = w_time + w_showcase + w_price + w_discount
    return int(w)


def items_rec(nick, mdb, rdb):
    cur = mdb.items.find({'nick':nick}, fields = ['list_time', 'has_discount', 'has_showcase', 'price', 'title'])
    for i in cur:
        try:
            w = cal_item_weight(i)
            rdb.zincrby(nick, i['_id'], w)
        except Exception as e:
            rlog.warning('item_rec fail of [%s]: %s' %(repr(i['_id']), repr(e)))

def testing_items_weight(nick):
    m = pymongo.Connection('127.0.0.1:57324')
    rdb = redis.StrictRedis(host='127.0.0.1', port=56379, db=10)
    items_rec(nick, m.taogold, rdb)
    res = rdb.zrange(nick, 0, -1, withscores=True)
    import pprint
    pprint.pprint(res)


if __name__ == '__main__':
    testing_items_weight('古代')





